package com.oracle.lingshangejia.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;



import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint({"NewApi", "Registered"})
@TargetApi(9)
public class DownLoadService extends Service {

    private static CallBack mCallBack;
    private static DownLoadService downLoadService;
    private MyBroadcast myBroadcast;
    private DownloadManager manager;
    private long refernece;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static final void Start(Context context, CallBack callBack) {
        if (downLoadService == null) {
            mCallBack = callBack;
            context.startService(new Intent(context, DownLoadService.class));
            Log.e("DownLoadService", "Start");
        } else {
            callBack.onCallBack(downLoadService);
            Log.e("DownLoadService", "callBack");
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        downLoadService = this;
        this.manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        this.myBroadcast = new MyBroadcast();
        this.registerReceiver(myBroadcast, intentFilter);

        if (mCallBack != null) {
            mCallBack.onCallBack(downLoadService);
            Log.e("DownLoadService", "onCreate");
        }
    }

    private String name_apk,s_apk;

    public void updata(String url, String name, String s) {

        name_apk = name;
        s_apk = s;
        DownloadManager.Request o = new DownloadManager.Request(Uri.parse(url));
        o.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        o.setVisibleInDownloadsUi(true);
        o.setDescription("岭尚E家应用下载");
        o.allowScanningByMediaScanner();
        o.setMimeType("application/vnd.android.package-archive");
        o.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS,name + s);
//        o.setDestinationInExternalPublicDir("/JnShop/", name + s);
//        o.setDestinationInExternalPublicDir(Environment.DIRECTORY_DCIM, name + s);
        refernece = this.manager.enqueue(o);
        query();
    }

    private DownloadManager.Query downloadQuery;
    private Cursor cursor;
    private Timer timer;
    // 查询下载进度，文件总大小多少，已经下载多少？
    private void query() {

        if (timer == null){

            timer = new Timer();
        }

        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                if (downloadQuery == null){

                    downloadQuery = new DownloadManager.Query();
                }

                downloadQuery.setFilterById(refernece);
                cursor = manager.query(downloadQuery);
                if (cursor != null && cursor.moveToFirst()) {

                    int totalSizeBytesIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                    int bytesDownloadSoFarIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);

                    // 下载的文件总大小
                    int totalSizeBytes = cursor.getInt(totalSizeBytesIndex);

                    // 截止目前已经下载的文件总大小
                    int bytesDownloadSoFar = cursor.getInt(bytesDownloadSoFarIndex);

                    mCallBack.onLoadProgress(bytesDownloadSoFar,totalSizeBytes);

                    if (bytesDownloadSoFar == totalSizeBytes){

                        mCallBack.onEnd();

                        timer.cancel();
                        timer = null;
                        mCallBack = null;
                    }

                    cursor.close();
                }
            }
        },500,500);
    }

    public interface CallBack {
        void onCallBack(DownLoadService var1);
        void onLoadProgress(double progress, double total);
        void onEnd();
    }

    private class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            if (refernece == myDwonloadID){

                Intent s = new Intent();

                Uri u;

                File apkFile = getExternalFilesDir("DownLoad/" + name_apk + s_apk);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // UpdateConfig.FILE_PROVIDER_AUTH 即是在清单文件中配置的authorities
                    // 给目标应用一个临时授权
                    s.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    u = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/JnShop/" + name_apk + s_apk));
                    u = FileProvider.getUriForFile(context, "com.lc.upauction.fileprovider", apkFile);
                } else {

                    u = manager.getUriForDownloadedFile(refernece);
                }

                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, u));

                try {

                    s.setAction("android.intent.action.VIEW");
                    s.addCategory("android.intent.category.DEFAULT");
//                    String type = getMIMEType(new File(new URI(u.toString())));
                    s.setDataAndType(u, "application/vnd.android.package-archive");
                    s.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    DownLoadService.this.startActivity(s);
                    DownLoadService.this.stopSelf();
                }catch (Exception e){

                   // UtilToast.show("无支持此类格式的应用");
                }
            }

        }

    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     * @param file
     */
    private String getMIMEType(File file) {

        String type="*/*";
        String fName = file.getName();
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if(dotIndex < 0){
            return type;
        }
        /* 获取文件的后缀名*/
        String end=fName.substring(dotIndex,fName.length()).toLowerCase();
        if(end=="")return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for(int i=0;i<MIME_MapTable.length;i++){
            if(end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private final String[][] MIME_MapTable={
            //{后缀名，MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-JavaScript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"},
            {"", "*/*"}
    };

    @Override
    public void onDestroy() {
        downLoadService = null;
        this.unregisterReceiver(this.myBroadcast);
        super.onDestroy();
    }
}
